package tungsten.pb.module;

import com.google.protobuf.*;
import com.google.protobuf.Message;
import tungsten.base.server.BaseClient;
import tungsten.base.thread.ThreadPool;
import tungsten.pb.protocol.Heads;

import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created by Lv on 2016/6/24.
 */
public abstract class Module
{
    public static final String MESSAGE_THREAD = "MESSAGE_THREAD";

    private final Parser<? extends Message> parser;
    public Module(Parser<? extends Message> parser)
    {
        this.parser = parser;
    }

    final public void onMessage(BaseClient client, Heads.Head head)
    {
        try
        {
            ThreadPool.submit(MESSAGE_THREAD,new Packet(client,head,parser.parseFrom(head.getBytes())));
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    protected abstract void onMessage(BaseClient client, Heads.Head head,Message message);

    private class Packet implements Runnable
    {
        private final BaseClient client;
        private final Message message;
        private final Heads.Head head;

        public Packet(BaseClient client, Heads.Head head,Message message)
        {
            this.client = client;
            this.head = head;
            this.message = message;
        }

        @Override
        public void run()
        {
            onMessage(client,head,message);
        }
    }
}
